// 待办事项数组
let todos = [];

// 当前排序方式
let currentSort = 'created';

// 当前标签筛选
let currentTagFilter = 'all';

// 常用标签颜色映射
const tagColors = {};

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    // 从本地存储加载待办事项
    loadTodos();
    
    // 渲染待办事项列表
    renderTodos();
    
    // 渲染标签筛选器
    renderTagFilters();
    
    // 添加按钮点击事件 - 打开空白的编辑模态框
    document.getElementById('add-button').addEventListener('click', () => openEditModal());
    
    // 清除已完成按钮点击事件
    document.getElementById('clear-completed').addEventListener('click', clearCompleted);
    
    // 排序按钮点击事件
    document.getElementById('sort-created').addEventListener('click', () => sortTodos('created'));
    document.getElementById('sort-completed').addEventListener('click', () => sortTodos('completed'));
    document.getElementById('sort-priority').addEventListener('click', () => sortTodos('priority'));
    document.getElementById('sort-due').addEventListener('click', () => sortTodos('due'));
    
    // 模态框关闭按钮事件
    document.querySelector('.close-modal').addEventListener('click', closeModal);
    document.querySelector('.cancel-btn').addEventListener('click', closeModal);
    
    // 添加标签按钮事件
    document.getElementById('add-tag-btn').addEventListener('click', addTag);
    
    // 表单提交事件
    document.getElementById('detail-form').addEventListener('submit', (e) => {
        e.preventDefault();
        saveTodoDetails();
    });
    
    // 点击模态框外部关闭
    window.addEventListener('click', (e) => {
        const modal = document.getElementById('detail-modal');
        if (e.target === modal) {
            closeModal();
        }
    });
});

// 加载待办事项
function loadTodos() {
    const savedTodos = localStorage.getItem('todos');
    if (savedTodos) {
        todos = JSON.parse(savedTodos);
    }
}

// 保存待办事项到本地存储
function saveTodos() {
    localStorage.setItem('todos', JSON.stringify(todos));
}

// 添加待办事项
function addTodo(todoData) {
    const newTodo = {
        id: Date.now(),
        text: todoData.text,
        completed: false,
        createdAt: new Date().toISOString(),
        priority: todoData.priority || 'none',
        description: todoData.description || '',
        dueDate: todoData.dueDate || '',
        tags: todoData.tags || []
    };
    
    todos.unshift(newTodo);
    saveTodos();
    renderTodos();
    renderTagFilters();
}

// 删除待办事项
function deleteTodo(id) {
    todos = todos.filter(todo => todo.id !== id);
    saveTodos();
    renderTodos();
    renderTagFilters();
}

// 切换待办事项完成状态
function toggleTodo(id) {
    todos = todos.map(todo => {
        if (todo.id === id) {
            return { ...todo, completed: !todo.completed };
        }
        return todo;
    });
    
    saveTodos();
    renderTodos();
}

// 清除已完成的待办事项
function clearCompleted() {
    todos = todos.filter(todo => !todo.completed);
    saveTodos();
    renderTodos();
    renderTagFilters();
}

// 排序待办事项
function sortTodos(sortBy) {
    currentSort = sortBy;
    
    // 更新排序按钮状态
    document.querySelectorAll('.sort-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.getElementById(`sort-${sortBy}`).classList.add('active');
    
    renderTodos();
}

// 渲染待办事项列表
function renderTodos() {
    const todoList = document.getElementById('todo-list');
    todoList.innerHTML = '';
    
    // 根据当前排序方式对待办事项进行排序
    const sortedTodos = [...todos];
    
    // 优先级顺序映射（值越小优先级越高）
    const priorityOrder = { 'high': 0, 'medium': 1, 'low': 2, 'none': 3 };
    
    switch (currentSort) {
        case 'created':
            sortedTodos.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
            break;
        case 'completed':
            sortedTodos.sort((a, b) => {
                if (a.completed === b.completed) {
                    return new Date(b.createdAt) - new Date(a.createdAt);
                }
                return a.completed ? 1 : -1;
            });
            break;
        case 'priority':
            sortedTodos.sort((a, b) => {
                if (priorityOrder[a.priority] === priorityOrder[b.priority]) {
                    return new Date(b.createdAt) - new Date(a.createdAt);
                }
                return priorityOrder[a.priority] - priorityOrder[b.priority];
            });
            break;
        case 'due':
            sortedTodos.sort((a, b) => {
                // 无截止日期的排在最后
                if (!a.dueDate && !b.dueDate) return new Date(b.createdAt) - new Date(a.createdAt);
                if (!a.dueDate) return 1;
                if (!b.dueDate) return -1;
                
                // 按截止日期排序
                return new Date(a.dueDate) - new Date(b.dueDate);
            });
            break;
    }
    
    // 根据标签筛选
    const filteredTodos = currentTagFilter === 'all' 
        ? sortedTodos 
        : sortedTodos.filter(todo => todo.tags.includes(currentTagFilter));
    
    // 渲染筛选后的待办事项
    filteredTodos.forEach(todo => {
        const li = document.createElement('li');
        li.className = `todo-item ${todo.completed ? 'completed' : ''}`;
        
        // 创建优先级标记
        const priorityMarker = document.createElement('div');
        priorityMarker.className = `priority-marker priority-${todo.priority}`;
        
        // 创建复选框
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.className = 'todo-checkbox';
        checkbox.checked = todo.completed;
        checkbox.addEventListener('change', () => toggleTodo(todo.id));
        
        // 创建内容容器
        const contentDiv = document.createElement('div');
        contentDiv.className = 'todo-content';
        
        // 创建文本元素
        const textSpan = document.createElement('div');
        textSpan.className = 'todo-text';
        textSpan.textContent = todo.text;
        
        // 添加描述（如果有）
        if (todo.description) {
            const descSpan = document.createElement('div');
            descSpan.className = 'todo-details';
            descSpan.textContent = todo.description.length > 50 
                ? todo.description.substring(0, 50) + '...' 
                : todo.description;
            contentDiv.appendChild(textSpan);
            contentDiv.appendChild(descSpan);
        } else {
            contentDiv.appendChild(textSpan);
        }
        
        // 添加创建时间
        const createdAtDiv = document.createElement('div');
        createdAtDiv.className = 'todo-created-at';
        createdAtDiv.textContent = `创建时间: ${formatDate(todo.createdAt)}`;
        contentDiv.appendChild(createdAtDiv);

        // 添加截止日期（如果有）
        if (todo.dueDate) {
            const dueDate = new Date(todo.dueDate);
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            
            const dueDateSpan = document.createElement('div');
            dueDateSpan.className = 'todo-due-date';
            
            // 检查是否过期
            if (dueDate < today) {
                dueDateSpan.classList.add('overdue');
                dueDateSpan.textContent = `截止日期: ${formatDate(todo.dueDate)} (已过期)`;
            } else {
                dueDateSpan.textContent = `截止日期: ${formatDate(todo.dueDate)}`;
            }
            
            contentDiv.appendChild(dueDateSpan);
        }
        
        // 添加标签（如果有）
        if (todo.tags && todo.tags.length > 0) {
            const tagsDiv = document.createElement('div');
            tagsDiv.className = 'todo-tags';
            
            todo.tags.forEach(tag => {
                const tagSpan = document.createElement('span');
                tagSpan.className = 'tag';
                tagSpan.textContent = tag;
                
                // 设置标签颜色
                if (tagColors[tag]) {
                    tagSpan.style.backgroundColor = tagColors[tag];
                } else {
                    // 为新标签生成随机颜色
                    const color = generateTagColor(tag);
                    tagColors[tag] = color;
                    tagSpan.style.backgroundColor = color;
                }
                
                tagsDiv.appendChild(tagSpan);
            });
            
            contentDiv.appendChild(tagsDiv);
        }
        
        // 创建操作按钮容器
        const actionsDiv = document.createElement('div');
        actionsDiv.className = 'todo-actions';
        
        // 创建编辑按钮
        const editButton = document.createElement('button');
        editButton.className = 'edit-btn';
        editButton.textContent = '编辑';
        editButton.addEventListener('click', () => openEditModal(todo));
        
        // 创建删除按钮
        const deleteButton = document.createElement('button');
        deleteButton.className = 'delete-btn';
        deleteButton.textContent = '删除';
        deleteButton.addEventListener('click', () => deleteTodo(todo.id));
        
        // 将按钮添加到操作容器
        actionsDiv.appendChild(editButton);
        actionsDiv.appendChild(deleteButton);
        
        // 将所有元素添加到列表项
        li.appendChild(priorityMarker);
        li.appendChild(checkbox);
        li.appendChild(contentDiv);
        li.appendChild(actionsDiv);
        
        // 将列表项添加到待办事项列表
        todoList.appendChild(li);
    });
}

// 打开编辑模态框
function openEditModal(todo) {
    const modal = document.getElementById('detail-modal');
    const titleInput = document.getElementById('edit-title');
    const descriptionInput = document.getElementById('edit-description');
    const dueDateInput = document.getElementById('edit-due-date');
    const prioritySelect = document.getElementById('edit-priority');
    const todoIdInput = document.getElementById('edit-todo-id');
    const modalTitle = document.getElementById('modal-title');
    
    // 清空标签容器
    const tagsContainer = document.getElementById('tags-container');
    tagsContainer.innerHTML = '';
    
    if (todo) {
        // 编辑现有待办事项
        modalTitle.textContent = '编辑待办事项';
        titleInput.value = todo.text;
        descriptionInput.value = todo.description || '';
        dueDateInput.value = todo.dueDate || '';
        prioritySelect.value = todo.priority;
        todoIdInput.value = todo.id;
        
        // 添加现有标签
        if (todo.tags && todo.tags.length > 0) {
            todo.tags.forEach(tag => {
                addTagToContainer(tag);
            });
        }
    } else {
        // 创建新待办事项
        modalTitle.textContent = '添加待办事项';
        titleInput.value = '';
        descriptionInput.value = '';
        dueDateInput.value = '';
        prioritySelect.value = 'none';
        todoIdInput.value = '';
    }
    
    // 显示模态框
    modal.style.display = 'block';
}

// 关闭模态框
function closeModal() {
    const modal = document.getElementById('detail-modal');
    modal.style.display = 'none';
    
    // 清空表单
    document.getElementById('detail-form').reset();
    document.getElementById('tags-container').innerHTML = '';
}

// 保存待办事项详情
function saveTodoDetails() {
    const todoId = document.getElementById('edit-todo-id').value;
    const title = document.getElementById('edit-title').value.trim();
    const description = document.getElementById('edit-description').value.trim();
    const dueDate = document.getElementById('edit-due-date').value;
    const priority = document.getElementById('edit-priority').value;
    
    // 收集标签
    const tagsContainer = document.getElementById('tags-container');
    const tagElements = tagsContainer.querySelectorAll('.tag');
    const tags = Array.from(tagElements).map(el => el.textContent.replace('×', '').trim());
    
    if (title) {
        if (todoId) {
            // 更新现有待办事项
            todos = todos.map(todo => {
                if (todo.id === parseInt(todoId)) {
                    return {
                        ...todo,
                        text: title,
                        description: description,
                        dueDate: dueDate,
                        priority: priority,
                        tags: tags
                    };
                }
                return todo;
            });
        } else {
            // 创建新待办事项
            addTodo({
                text: title,
                description: description,
                dueDate: dueDate,
                priority: priority,
                tags: tags
            });
        }
        
        saveTodos();
        renderTodos();
        renderTagFilters();
        closeModal();
    } else {
        alert('标题不能为空！');
    }
}

// 添加标签
function addTag() {
    const tagInput = document.getElementById('edit-tags');
    const tag = tagInput.value.trim();
    
    if (tag) {
        addTagToContainer(tag);
        tagInput.value = '';
    }
}

// 将标签添加到容器
function addTagToContainer(tag) {
    const tagsContainer = document.getElementById('tags-container');
    
    // 检查标签是否已存在
    const existingTags = Array.from(tagsContainer.querySelectorAll('.tag'))
        .map(el => el.textContent.replace('×', '').trim());
    
    if (!existingTags.includes(tag)) {
        const tagSpan = document.createElement('span');
        tagSpan.className = 'tag';
        
        // 设置标签颜色
        if (tagColors[tag]) {
            tagSpan.style.backgroundColor = tagColors[tag];
        } else {
            // 为新标签生成随机颜色
            const color = generateTagColor(tag);
            tagColors[tag] = color;
            tagSpan.style.backgroundColor = color;
        }
        
        tagSpan.textContent = tag;
        
        // 添加删除按钮
        const deleteBtn = document.createElement('span');
        deleteBtn.className = 'tag-delete';
        deleteBtn.textContent = '×';
        deleteBtn.addEventListener('click', () => {
            tagsContainer.removeChild(tagSpan);
        });
        
        tagSpan.appendChild(deleteBtn);
        tagsContainer.appendChild(tagSpan);
    }
}

// 渲染标签筛选器
function renderTagFilters() {
    const tagFilters = document.getElementById('tag-filters');
    const allTags = new Set();
    
    // 收集所有标签
    todos.forEach(todo => {
        if (todo.tags) {
            todo.tags.forEach(tag => allTags.add(tag));
        }
    });
    
    // 清空现有标签筛选器（保留"全部"选项）
    const allFilter = tagFilters.querySelector('[data-tag="all"]');
    tagFilters.innerHTML = '';
    tagFilters.appendChild(allFilter);
    
    // 添加标签筛选器
    allTags.forEach(tag => {
        const tagSpan = document.createElement('span');
        tagSpan.className = 'tag-filter';
        tagSpan.textContent = tag;
        tagSpan.dataset.tag = tag;
        
        if (tag === currentTagFilter) {
            tagSpan.classList.add('active');
        }
        
        tagSpan.addEventListener('click', () => filterByTag(tag));
        tagFilters.appendChild(tagSpan);
    });
    
    // 更新"全部"标签的状态
    if (currentTagFilter === 'all') {
        allFilter.classList.add('active');
    } else {
        allFilter.classList.remove('active');
    }
    
    // 添加"全部"标签的点击事件
    allFilter.addEventListener('click', () => filterByTag('all'));
}

// 按标签筛选
function filterByTag(tag) {
    currentTagFilter = tag;
    
    // 更新筛选器状态
    document.querySelectorAll('.tag-filter').forEach(filter => {
        if (filter.dataset.tag === tag) {
            filter.classList.add('active');
        } else {
            filter.classList.remove('active');
        }
    });
    
    renderTodos();
}

// 生成标签颜色
function generateTagColor(tag) {
    // 使用标签文本生成一个稳定的颜色
    let hash = 0;
    for (let i = 0; i < tag.length; i++) {
        hash = tag.charCodeAt(i) + ((hash << 5) - hash);
    }
    
    // 生成柔和的颜色
    const hue = Math.abs(hash % 360);
    return `hsl(${hue}, 70%, 50%)`;
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}